package utils;

import com.alibaba.fastjson.JSON;
import constants.APIErrorDict;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xiabin on 2017/10/17.
 */
public class ExceptionHandler implements HandlerExceptionResolver {

    private static final Logger LOG = LoggerFactory.getLogger(ExceptionHandler.class);

    @Override
    @ResponseBody
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        /*  使用response返回 */
        ModelAndView mv = new ModelAndView();
        //设置状态码
        response.setStatus(HttpStatus.OK.value());
        //设置ContentType
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        //避免乱码
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        APIResult res = new APIResult(APIErrorDict.SYSERROR);
        try {
            response.getWriter().write(JSON.toJSONString(res));
        } catch (IOException e) {
            LOG.error("与客户端通讯异常:" + e.getMessage(), e);
        }

        LOG.error("接口异常信息:" + ex.getMessage(), ex);
        return mv;
    }
}
